package com.le.tester.book.concurrentjavafight.l_8_5;

//import cn.hutool.core.date.DateTime;
//import cn.hutool.core.date.DateUtil;

import java.util.*;
import java.util.concurrent.*;

/**
 * createTime：2022/12/29 14:13
 * description：串行程序修改成并行
 */
public class Demo {
    //串行
    void processSequentially(List<Integer> element) {

        //single thread
        for (Integer item : element) {
            System.out.println(process(item));
        }
    }

    //并行
    void processParallel(Executor executor, List<Integer> element) {
        for (final Integer item : element) {
            executor.execute(() -> process(item));
        }
    }

    private Integer process(Integer item) {
        item = item + 1;
        return item;
    }

    //串行递归
    public <T> void sequentialRecursive(List<T> nodes, Collection<T> results) {
        for (T n : nodes) {
            results.add(n);
            //循环中疯狂递归
            sequentialRecursive(new ArrayList<>(), results);
        }
    }

    //并行递归
    public <T> void parallelRecursive(final Executor executor, List<T> nodes, final Collection<T> results) {
        for (final T n : nodes) {
            executor.execute(() -> results.add(n));
        }
        //循环结束后递归
        parallelRecursive(executor, new ArrayList<>(), results);
    }

    //获取并行结果
    public <T> Collection<T> getParallelResults(List<T> nodes) throws InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        Queue<T> resultQueue = new ConcurrentLinkedQueue<T>();
        parallelRecursive(service, nodes, resultQueue);
        service.shutdown();
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
        return resultQueue;
    }


}
